package com.lingkang.sales.config.aop.aspect;

import cn.hutool.core.util.ArrayUtil;
import com.lingkang.sales.config.exception.VerificationException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author linke
 * @date 2020/11/19 23:29
 * @description 若分页入参为空，则赋默认值
 */
@Aspect
@Component
public class defaultPageValidAop {

  /**
   * 切入点
   */
  @Pointcut("@annotation(com.lingkang.sales.config.aop.DefaultPageValid)")
  public void annotationPointcut() {
  }

  @Around("annotationPointcut()")
  public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    //获取参数名称
    String[] parameterNames = methodSignature.getParameterNames();
    // 获取page、size的下标
    int page = ArrayUtil.indexOf(parameterNames, "page");
    int size = ArrayUtil.indexOf(parameterNames, "size");
    if(size==-1){
      throw new VerificationException("入参size不能为空！");
    }
    // args是有下标的，断点显示为空，这里需要注意
    Object[] args = joinPoint.getArgs();
    if (args[page] == null) {
      args[page] = 1;//默认值为1
    }
    if (args[size] == null) {
      args[size] = 10;//默认值为10
    }
    return joinPoint.proceed(args);
  }

}
